<template>
  <div class="main">
    <!-- 头部标题栏 -->
    <van-nav-bar
      class="navbar"
      title="核酸检测申请"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="content">
      <!-- 用户信息卡 -->
      <van-row class="user_card" v-if="userList">
        <van-col span="24"
          ><div class="name_card">{{ userList.name }}</div></van-col
        >
        <van-col span="24"
          ><div class="id_card">{{ userList.id_number | hidden }}</div></van-col
        >
      </van-row>
      <!-- 预约时间 -->
      <div class="order_time">
        <p class="office">科室-保健科</p>
        <p>选择预约时间</p>
      </div>

      <!-- 日期选择 -->
      <div class="calendar">
        <div v-for="(item, index) in 7" :key="index">
          <p>{{ getDay(index) }}</p>
          <p>
            <button
              @click="getButtonClick(item)"
              :class="{
                activeColor: activeIndex == index,
                deactiveColor: activeIndex != index,
              }"
            >
              {{ getDate(index) }}
            </button>
          </p>
        </div>
      </div>
      <!-- 存货 -->
      <div class="store">
        <p>检测存量</p>
        <div class="morning" v-if="dayone">
          <button
            v-for="(item, index) in dayone"
            :key="index"
            :class="{ havestore: item > 0 }"
            :disabled="item == 0 ? true : false"
            @click="submitOrder(index)"
          >
            {{ index }}剩余{{ item }}
          </button>
        </div>
      </div>
      <!-- 注意事项 -->
      <div class="attention">
        <p>预约须知：</p>
        <p>1.核酸检测结果有效期：7天。</p>
        <p>
          2.受检者必须全程佩戴口罩，采样时将口罩封装在塑料袋里放入口袋中，采样后立即佩戴好口罩。
        </p>
        <p>
          3、新冠病毒核酸检测（咽拭子）采样前2小时不进食、不吸烟、不饮酒，采样前清水漱口。
        </p>
        <p>4、预约成功后如须退款，请于我院退费窗口办理。</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      storeList: null, //存货列表
      dayone: null, //格式化后的存货列表
      activeIndex: 0,
      userList: null,
      nowDate: 0, //存储选中的日期

    };
  },
  mounted() {
    // 进入界面加载day1存货
    this.getStore(1);
    // 进入界面加载就诊人信息
    this.getSinglePatient();
  },
  methods: {
    // 点击日期按钮切换axios请求数据
    getButtonClick(value) {
      this.activeIndex = value - 1;
      this.nowDate = value - 1;
      this.getStore(value);
    },
    // axios获取后台疫苗存货
    getStore(value) {
      this.axios
        .get(`${this.$base}hospital/registration?id=1`)
        .then((res) => {
          this.storeList = res.data.data[0];
          // console.log(this.storeList);
          this.dayone = JSON.parse(this.storeList["day" + value]);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 用户选择预约时间，并提交
    submitOrder(time) {
      let test_name = sessionStorage.getItem('category') == 1 ? '新型冠状病毒灭活疫苗' : '新型冠状病毒核酸检测（咽拭子）'
      let test_category = sessionStorage.getItem('category') == 1 ? '疫苗预约' : '核酸检测'
      // console.log(test_name);
      this.$dialog
        .confirm({
          title: this.userList.name,
          message: test_name,
        })
        .then(() => {
          let url = `${this.$base}appointment`;
          let arr = ["day1", "day2", "day3", "day4", "day5", "day6", "day7"];
          let appoint_time = this.formatDate(this.nowDate, time) / 1000; //把毫秒时间戳转为秒
          // console.log(appoint_time);
          let params = {
            type: 0, //0是核酸 1 是疫苗
            name: test_category,
            hid: sessionStorage.getItem('hid'), //医院id
            pid: sessionStorage.getItem('patientid'), //病人id
            test_name: test_name,
            state: 0, //0是预约成功，1是已完成（1在后台改，此处全是0）
            index: arr[this.nowDate],
            whichtime: time, //哪个时间段 9:00或10:00
            appoint_time: appoint_time,
          };
  
          // 这是提交预约申请
          this.axios
            .post(url, this.$qs.stringify(params))
            .then((res) => {
      
              if (res.data.code == 200) {
                this.$router.push("/ordersuccess");
              }
            })
            .catch((err) => {
              console.error(err);
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    // 请求单个就诊人数据，此id是前置页面传入sessionStorage

    getSinglePatient() {
      let patientid = sessionStorage.getItem('patientid')
      this.axios
        .get(`${this.$base}patient/single_detail?id=${patientid}`)
        .then((res) => {
          // console.log(res.data)
          this.userList = res.data.data;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 对时间数据进行封装
    formatDate(date, time) {
      let oneday = 24 * 60 * 60 * 1000;
      let time_arr = time.split(":");
      let extra_time = time_arr[0] * 60 * 60 * 1000 + time_arr[1] * 60 * 1000;
      var now = new Date(new Date().toLocaleDateString()).getTime();
      var timestamp = now + date * oneday + extra_time;
      return timestamp;
    },
  },
  computed: {
    getDay() {
      return function (value) {
        let oneday = 24 * 60 * 60 * 1000;
        var now = new Date();
        var timestamp = now.getTime() + value * oneday;
        var correct = new Date(timestamp);
        var day = correct.getDay();
        var weeks = new Array(
          "周日",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六"
        );
        var week = weeks[day];
        return week;
      };
    },
    getDate() {
      return function (value) {
        let oneday = 24 * 60 * 60 * 1000;
        var now = new Date();
        var timestamp = now.getTime() + value * oneday;
        var correct = new Date(timestamp);
        var day = correct.getDate();
        return day;
      };
    },
  },
  filters: {
    hidden: function (value) {
      return (value = value.replace(/^(.{4})(?:\d+)(.{4})$/, "$1******$2"));
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  background-color: #fdfeff;
}
.van-nav-bar {
  background-color: #1074ff;
  opacity: 0.8;
  /deep/ .van-nav-bar__title {
    color: #fff;
  }
  /deep/ .van-icon-arrow-left {
    color: #fff;
  }
}
.content {
  width: 90%;
  height: 400px;
  margin: 0 auto;
}
.user_card {
  margin-top: 10px;

  margin: 20px auto;
  background-color: #f5f9ff;
  border-radius: 5px;
  .name_card {
    margin-top: 20px;
    margin-left: 10px;
  }
  .id_card {
    margin-top: 10px;
    margin-left: 10px;
    margin-bottom: 20px;
    color: #aaaaaa;
    font-size: 14px;
  }
}
.order_time {
  margin: 10px auto;
  .office {
    color: #aaaaaa;
    font-size: 14px;
  }
}
.calendar {
  box-shadow: 0 0 0 1px #f2f2f2;
  border-radius: 3px;
  display: flex;
  background-color: #fff;
  > div {
    flex: 1;
    color: #aaaaaa;
    font-size: 14px;
    text-align: center;
    p {
      font-size: 13px;
    }

    button {
      border: none;
      outline: none;
      width: 80%;
      font-size: 16px;
      height: 30px;
      border-radius: 15px;
    }
    .deactiveColor {
      background-color: #e6f1ff;

      color: black;
    }
    .activeColor {
      background-color: #006eff;
      color: white;
    }
  }
}

.store {
  p {
    font-size: 14px;
    color: #aaaaaa;
  }

  .morning {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    button {
      border: none;
      outline: none;
      width: 30%;
      margin-bottom: 15px;
      font-size: 13px;
      height: 25px;
      text-align: center;
      line-height: 22px;
      border-radius: 4px;
      color: #aaaaaa;
      background-color: #f2f2f2;
    }
    .havestore {
      color: #006eff;
      background-color: #eff6ff;
    }
  }
}

.attention {
  box-shadow: 0 0 0 1px #f2f2f2;
  border-radius: 3px;
  background-color: #fff;
  padding-left: 10px;
  color: grey;
  font-size: 14px;
  margin-bottom: 15px;
  overflow: hidden;
  p {
    margin: 4px;
  }
  // padding-top: 3px;
}

/deep/ .van-button__content {
  color: green !important;
}
</style>